package com.cainiao.aop;

import com.cainiao.mapper.OperateLogMapper;
import com.cainiao.pojo.OperateLog;
import com.cainiao.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.cainiao.annotation.Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable
    {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateEmpId = (Integer) claims.get("id");
        String operateEmpName = (String) claims.get("username");
        LocalDateTime operateTime = LocalDateTime.now();
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        Long start= System.currentTimeMillis();
        Object result = pjp.proceed();
        //判断是否为null
        String returnValue = result == null ? "" : result.toString();
        Long end = System.currentTimeMillis();
        long costTime = end - start;
        OperateLog log = new OperateLog(null, operateEmpId, operateTime, className, methodName, methodParams, returnValue, costTime,operateEmpName);
        operateLogMapper.insert(log);
        return result;
    }
}
